﻿using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace DistributedVisionRunner.Module.ViewModels
{
    public class WeightCollectionViewModel : BindableBase
    {

        #region private fields

        private bool _needToSave;

        #endregion

        #region props

        public List<WeightItemViewModel> WeightItems { get; }

        public ICommand ImportFromClipboardCommand { get; }

        public int Index { get; set; }

        public bool NeedToSave
        {
            get => _needToSave;
            set => SetProperty(ref _needToSave, value);
        }

        #endregion


        #region ctor

        public WeightCollectionViewModel(List<WeightItemViewModel> weightItems)
        {
            WeightItems = weightItems;
            ImportFromClipboardCommand = new DelegateCommand(() =>
            {
                var text = Clipboard.GetText(TextDataFormat.Text);

                List<double> TrySplitCsv(string content, char[] possibleDelimiters, int numberCount)
                {
                    foreach (var delimiter in possibleDelimiters)
                    {
                        var textArray = content.Split(delimiter).Where(t => !string.IsNullOrWhiteSpace(t)).ToArray();
                        if (textArray.Length != numberCount) continue;
                        try
                        {
                            return textArray.Select(double.Parse).ToList();

                        }
                        catch (FormatException)
                        {
                        }

                    }

                    return null;
                }

                var numbers = TrySplitCsv(text, new[] { ' ', ',', '\t', '\n' }, weightItems.Count);

                string message;
                if (numbers != null)
                {
                    for (int itemIndex = 0; itemIndex < weightItems.Count; itemIndex++)
                    {
                        var item = weightItems[itemIndex];
                        var value = numbers[itemIndex];
                        item.Weight = value;
                    }

                    message = "成功导入一组补偿";
                }
                else
                {
                    message = "导入失败, 请检查复制内容的长度是否和补偿个数一致, 或者内容是否含有非数字";
                }

                MessageBox.Show(message);
            });
        }


        #endregion




    }
}